package com.jumi.microservice.service.usercash.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.bean.OrderProducerBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.config.CpsUserCashConfig;
import com.jumi.microservice.constant.usercash.CpsUserCashStatusEnum;
import com.jumi.microservice.constant.usercash.CpsCashStatusEnum;
import com.jumi.microservice.constant.usercash.CpsCashTypeEnum;
import com.jumi.microservice.domain.MessageTemplate;
import com.jumi.microservice.dto.reponse.UserExternalResponse;
import com.jumi.microservice.dto.userWallet.WalletInOrOutRequest;
import com.jumi.microservice.dto.usercash.admin.*;
import com.jumi.microservice.dto.usercash.admin.OrderQueryRequest;
import com.jumi.microservice.entity.CpsUserCash;
import com.jumi.microservice.enumerate.CpsWalletTypeEnum;
import com.jumi.microservice.exception.CpsUserCashExceptionEnum;
import com.jumi.microservice.mapper.CpsUserCashMapper;
import com.jumi.microservice.rocketmq.RocketMqConfig;
import com.jumi.microservice.rocketmq.WalletSendMessageHandler;
import com.jumi.microservice.rocketmq.domian.CpsUserCashEvent;
import com.jumi.microservice.service.IUserExternalService;
import com.jumi.microservice.yzhpay.constant.*;
import com.jumi.microservice.yzhpay.dto.request.*;
import com.jumi.microservice.yzhpay.dto.response.Response;
import com.jumi.microservice.yzhpay.util.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Scw
 * @Date 2020-08-18 13:45
 */
@Service
public class AdminCpsUserCashService {
    @Resource
    private CpsUserCashMapper userCashMapper;
    @Resource
    private CpsUserCashConfig cpsUserCashConfig;
    @DubboReference
    private IUserExternalService iUserExternalService;
    @Resource
    OrderProducerBean producerBean;
    @Autowired
    RocketMqConfig rocketMqConfig;
    @Resource
    WalletSendMessageHandler sendMessageHandler;
    @Resource
    AdminCpsWalletInOrOutService adminCpsWalletInOrOutService;

    /**
     * 云账户
     * 公共返回方法
     */
    public Map<String, String> sysoutResult(Map<String, Object> result) {
        Map<String, String> returnMap = new HashMap<>();
        String statusCode = StringUtils.trim(result.get(XmlData.STATUSCODE));
        String dataJson;
        String yzhCode = "";
        String yzhData = "";
        String yzhMessage = "";
        String yzhRequestId = "";
        if ("200".equals(statusCode)) {
            dataJson = StringUtils.trim(result.get(XmlData.DATA));
            Response response = JsonUtil.fromJson(dataJson, Response.class);
            if (response != null) {
                yzhCode = response.getCode();
                if (response.getData() != null) yzhData = JSON.toJSONString(response.getData());
                yzhMessage = response.getMessage();
                yzhRequestId = response.getRequest_id();
            }
        }
        returnMap.put("statusCode", statusCode);
        returnMap.put("yzhCode", yzhCode);
        returnMap.put("yzhData", yzhData);
        returnMap.put("yzhMessage", yzhMessage);
        returnMap.put("yzhRequestId", yzhRequestId);
        return returnMap;
    }

    /**
     * 导出excel
     */
    public ExportExcelCommonResponse<ExportCpsUserCashResponse> exportExcel(ExportCpsUserCashRequest request) {
        request.checkRequest();
        QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("del_flag", DelFlag.NORMAL);
        //用户注册手机号
        if (request.getPhone() != null && !"".equals(request.getPhone())) {
            //根据手机号查询用户ID【用户服务提供接口】
            Integer uid = iUserExternalService.getUidByMobile(request.getPhone());
            if (uid != null && uid > 0) {
                queryWrapper.eq("uid", uid);
            } else {
                queryWrapper.eq("uid", DelFlag.NORMAL);
            }
        }
        //提现账户类型: 1-银行卡 2-支付宝
        if (request.getCashType() != null && request.getCashType() > 0) {
            queryWrapper.eq("cash_type", request.getCashType());
        }
        //提现状态: 0-申请中 1-提现处理中 2-审核失败 3-提现到账 4-提现失败
        if (request.getStatus() != null) {
            queryWrapper.eq("status", request.getStatus());
        }
        //创建开始时间
        if (request.getBeginTime() != null && !"".equals(request.getBeginTime())) {
            queryWrapper.ge("create_time", request.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //创建结束时间
        if (request.getEndTime() != null && !"".equals(request.getEndTime())) {
            queryWrapper.le("create_time", request.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //审核开始时间
        if (request.getCheckBeginTime() != null && !"".equals(request.getCheckBeginTime())) {
            queryWrapper.ge("check_time", request.getCheckBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //审核结束时间
        if (request.getCheckEndTime() != null && !"".equals(request.getCheckEndTime())) {
            queryWrapper.le("check_time", request.getCheckEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //支付开始时间
        if (request.getPayBeginTime() != null && !"".equals(request.getPayBeginTime())) {
            queryWrapper.ge("pay_time", request.getPayBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //支付结束时间
        if (request.getPayEndTime() != null && !"".equals(request.getPayEndTime())) {
            queryWrapper.le("pay_time", request.getPayEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //复选框选择ID
        if (request.getIdStr() != null && !"".equals(request.getIdStr())) {
            queryWrapper.in("id", request.getIdStr().split(","));
        }
        List<CpsUserCash> userCashes = userCashMapper.selectList(queryWrapper);
        List<ExportCpsUserCashResponse> list = new ArrayList<>();
        userCashes.forEach(userCash -> {
            ExportCpsUserCashResponse exportCpsUserCashResponse = new ExportCpsUserCashResponse();
            BeanUtils.copyProperties(userCash, exportCpsUserCashResponse);
            //根据用户ID，获取用户相关信息 姓名、手机号【用户服务提供接口】
            String realName = "";
            String phone = "";
            UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(userCash.getUid().intValue());
            if (userExternalResponse != null) {
                phone = userExternalResponse.getMobile();
                realName = userExternalResponse.getTrueName();
            }
            exportCpsUserCashResponse.setRealName(realName);
            exportCpsUserCashResponse.setPhone(phone);
            //提现账户类型对照
            CpsCashTypeEnum cpsCashTypeEnum = EnumUtil.getByCode(userCash.getCashType().intValue(), CpsCashTypeEnum.class);
            if (cpsCashTypeEnum != null) {
                exportCpsUserCashResponse.setCashTypeStr(cpsCashTypeEnum.getDesc());
            }
            //提现状态对照
            CpsCashStatusEnum cpsCashStatusEnum = EnumUtil.getByCode(userCash.getStatus().intValue(), CpsCashStatusEnum.class);
            if (cpsCashStatusEnum != null) {
                exportCpsUserCashResponse.setStatusStr(cpsCashStatusEnum.getDesc());
            }
            list.add(exportCpsUserCashResponse);
        });
        ExportExcelCommonResponse<ExportCpsUserCashResponse> response = new ExportExcelCommonResponse<>();
        response.setData(list);
        response.setFileName(System.currentTimeMillis() + ".xlsx");
        return response;
    }

    /**
     * 提现列表
     */
    public TableDataInfo<CpsUserCashListResponse> userCashList(CpsUserCashListRequest userCashListRequest) {
        QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("del_flag", DelFlag.NORMAL);
        //用户注册手机号
        if (userCashListRequest.getPhone() != null && !"".equals(userCashListRequest.getPhone())) {
            //根据手机号查询用户ID【用户服务提供接口】
            Integer uid = iUserExternalService.getUidByMobile(userCashListRequest.getPhone());
            if (uid != null && uid > 0) {
                queryWrapper.eq("uid", uid);
            } else {
                queryWrapper.eq("uid", DelFlag.NORMAL);
            }
        }
        //提现账户类型: 1-银行卡 2-支付宝
        if (userCashListRequest.getCashType() != null && userCashListRequest.getCashType() > 0) {
            queryWrapper.eq("cash_type", userCashListRequest.getCashType());
        }
        //提现状态: 0-申请中 1-提现处理中 2-审核失败 3-提现到账 4-提现失败
        if (userCashListRequest.getStatus() != null) {
            queryWrapper.eq("status", userCashListRequest.getStatus());
        }
        //创建开始时间
        if (userCashListRequest.getBeginTime() != null && !"".equals(userCashListRequest.getBeginTime())) {
            queryWrapper.ge("create_time", userCashListRequest.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //创建结束时间
        if (userCashListRequest.getEndTime() != null && !"".equals(userCashListRequest.getEndTime())) {
            queryWrapper.le("create_time", userCashListRequest.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //审核开始时间
        if (userCashListRequest.getCheckBeginTime() != null && !"".equals(userCashListRequest.getCheckBeginTime())) {
            queryWrapper.ge("check_time", userCashListRequest.getCheckBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //审核结束时间
        if (userCashListRequest.getCheckEndTime() != null && !"".equals(userCashListRequest.getCheckEndTime())) {
            queryWrapper.le("check_time", userCashListRequest.getCheckEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //支付开始时间
        if (userCashListRequest.getPayBeginTime() != null && !"".equals(userCashListRequest.getPayBeginTime())) {
            queryWrapper.ge("pay_time", userCashListRequest.getPayBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //支付结束时间
        if (userCashListRequest.getPayEndTime() != null && !"".equals(userCashListRequest.getPayEndTime())) {
            queryWrapper.le("pay_time", userCashListRequest.getPayEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        IPage<CpsUserCash> page = new Page<>(userCashListRequest.getPageNum(), userCashListRequest.getPageSize());
        page = userCashMapper.selectPage(page, queryWrapper);

        List<CpsUserCash> userCashs = page.getRecords();

        List<CpsUserCashListResponse> result = new ArrayList<>();

        for (CpsUserCash userCash : userCashs) {
            CpsUserCashListResponse userCashListResponse = new CpsUserCashListResponse();
            BeanUtils.copyProperties(userCash, userCashListResponse);
            //根据用户ID，获取用户相关信息 头像、昵称、姓名、手机号【用户服务提供接口】
            String nickName = "";
            String headUrl = "";
            String realName = "";
            String phone = "";
            UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(userCash.getUid().intValue());
            if (userExternalResponse != null) {
                nickName = userExternalResponse.getNickName();
                headUrl = userExternalResponse.getHeadUrl();
                realName = userExternalResponse.getTrueName();
                phone = userExternalResponse.getMobile();
            }
            userCashListResponse.setNickName(nickName);
            userCashListResponse.setHeadUrl(headUrl);
            userCashListResponse.setRealName(realName);
            userCashListResponse.setPhone(phone);
            //提现账户类型对照
            CpsCashTypeEnum cpsCashTypeEnum = EnumUtil.getByCode(userCash.getCashType().intValue(), CpsCashTypeEnum.class);
            if (cpsCashTypeEnum != null) {
                userCashListResponse.setCashTypeStr(cpsCashTypeEnum.getDesc());
            }
            //提现状态对照
            CpsCashStatusEnum cpsCashStatusEnum = EnumUtil.getByCode(userCash.getStatus().intValue(), CpsCashStatusEnum.class);
            if (cpsCashStatusEnum != null) {
                userCashListResponse.setStatusStr(cpsCashStatusEnum.getDesc());
            }
            result.add(userCashListResponse);
        }
        TableDataInfo<CpsUserCashListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;
    }

    /**
     * 审核信息
     */
    public CpsUserCashCheckInfoResponse checkInfo(CpsUserCashIdRequest userCashIdRequest) {
        CpsUserCashCheckInfoResponse userCashCheckInfoResponse = new CpsUserCashCheckInfoResponse();
        //查询当前信息
        if (userCashIdRequest.getId() > 0) {
            QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", CpsUserCashStatusEnum.STATUS_AUDIT_FAILED.getCode());
            queryWrapper.eq("del_flag", DelFlag.NORMAL);
            queryWrapper.eq("id", userCashIdRequest.getId());
            CpsUserCash userCash = userCashMapper.selectOne(queryWrapper);
            if (userCash == null) {
                throw new BaseException(CpsUserCashExceptionEnum.INFO_NO_EXIST.getCode(), CpsUserCashExceptionEnum.INFO_NO_EXIST.getMessage());
            }
            BeanUtils.copyProperties(userCash, userCashCheckInfoResponse);
        } else {
            throw new BaseException(CpsUserCashExceptionEnum.ID_LESS_ZERO.getCode(), CpsUserCashExceptionEnum.ID_LESS_ZERO.getMessage());
        }
        return userCashCheckInfoResponse;
    }

    /**
     * 审核拒绝，资金返还钱包
     */
    @org.springframework.transaction.annotation.Transactional
    public Boolean checkRefuse(CpsUserCashCheckRefuseRequest cashCheckRefuseRequest) {
        Long operatorId = cashCheckRefuseRequest.getOperatorId();
        String operatorName = cashCheckRefuseRequest.getOperatorName();

        boolean result = false;
        //查询当前信息
        if (cashCheckRefuseRequest.getId() > 0) {
            QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", CpsUserCashStatusEnum.STATUS_APPLY.getCode());
            queryWrapper.eq("del_flag", DelFlag.NORMAL);
            queryWrapper.eq("id", cashCheckRefuseRequest.getId());
            CpsUserCash userCash = userCashMapper.selectOne(queryWrapper);
            if (userCash == null) {
                throw new BaseException(CpsUserCashExceptionEnum.INFO_NO_EXIST.getCode(), CpsUserCashExceptionEnum.INFO_NO_EXIST.getMessage());
            }
            // 改变状态、记录原因
            int checkStatus = CpsUserCashStatusEnum.CHECK_STATUS_FAILED.getCode();
            userCash.setStatus((byte) checkStatus);
            userCash.setCheckTime(new Date());
            userCash.setCheckRemark(cashCheckRefuseRequest.getCheckRemark());
            userCash.setCheckOperatorId(operatorId);
            userCash.setCheckOperatorName(operatorName);
            int row = userCashMapper.updateById(userCash);
            if (row > 0) {
                Long userId = userCash.getUid();
                BigDecimal amount = userCash.getAmount();
                if (amount == null) {
                    amount = BigDecimal.valueOf(0);
                }
                int userCashId = userCash.getId();
                //添加收益
                WalletInOrOutRequest walletInOrOutRequest = new WalletInOrOutRequest();
                walletInOrOutRequest.setAmount(amount);
                walletInOrOutRequest.setRemark(CpsWalletTypeEnum.FAIL_WITHDRAW_IN.getMsg());
                walletInOrOutRequest.setUserId(userId);
                walletInOrOutRequest.setType(CpsWalletTypeEnum.FAIL_WITHDRAW_IN.getCode());
                walletInOrOutRequest.setOrderNo(userCash.getOrderNo());
                walletInOrOutRequest.setOrderId(userCashId);
                if (adminCpsWalletInOrOutService.walletIn(walletInOrOutRequest).getData()) {
                    //返回 状态
                    result = true;
                }
            }
        } else {
            throw new BaseException(CpsUserCashExceptionEnum.ID_LESS_ZERO.getCode(), CpsUserCashExceptionEnum.ID_LESS_ZERO.getMessage());
        }
        return result;
    }

    /**
     * 审核同意并打款
     * 打款失败，资金返还钱包
     */
    @org.springframework.transaction.annotation.Transactional
    public Boolean checkAgree(CpsUserCashCheckAgreeRequest userCashCheckAgreeRequest) {
        Long operatorId = userCashCheckAgreeRequest.getOperatorId();
        String operatorName = userCashCheckAgreeRequest.getOperatorName();
        //提现密码检测
        if (!userCashCheckAgreeRequest.getSecPassword().equals(cpsUserCashConfig.getSecPassword())) {
            throw new BaseException(CpsUserCashExceptionEnum.SEC_PASSWORD_WRONG.getCode(), CpsUserCashExceptionEnum.SEC_PASSWORD_WRONG.getMessage());
        }
        boolean result = false;
        //查询当前信息
        if (userCashCheckAgreeRequest.getId() > 0) {
            QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", CpsUserCashStatusEnum.STATUS_APPLY.getCode());
            queryWrapper.eq("del_flag", DelFlag.NORMAL);
            queryWrapper.eq("id", userCashCheckAgreeRequest.getId());
            CpsUserCash userCash = userCashMapper.selectOne(queryWrapper);
            if (userCash == null) {
                throw new BaseException(CpsUserCashExceptionEnum.INFO_NO_EXIST.getCode(), CpsUserCashExceptionEnum.INFO_NO_EXIST.getMessage());
            }
            // 改变状态、记录原因
            int checkStatus = CpsUserCashStatusEnum.CHECK_STATUS_PASSED.getCode();
            userCash.setStatus((byte) checkStatus);
            userCash.setCheckTime(new Date());
            userCash.setCheckOperatorId(operatorId);
            userCash.setCheckOperatorName(operatorName);
            int row = userCashMapper.updateById(userCash);
            if (row > 0) {
                /**
                 * 发送审核同意消息
                 */
                MessageTemplate messageTemplate = sendMessageHandler.getMessageTemplate(19);
                String appMessageContent = messageTemplate.getSmtAppContent();
                String stationMessageContent = messageTemplate.getSmtMessageContent();
                sendMessageHandler.sendMessage(appMessageContent,stationMessageContent,userCash.getUid(),19);
                /*
                 * 执行打款操作
                 */
                //单笔打款
                boolean isPay = this.singlePay(userCashCheckAgreeRequest.getId());
                if (isPay) {
                    result = true;
                }
            }
        } else {
            throw new BaseException(CpsUserCashExceptionEnum.ID_LESS_ZERO.getCode(), CpsUserCashExceptionEnum.ID_LESS_ZERO.getMessage());
        }
        return result;
    }

    /**
     * 批量审核同意并打款
     * 打款失败，资金返还钱包
     */
    public Boolean checkAgreeBatch(CpsUserCashCheckAgreeBatchRequest userCashCheckAgreeBatchRequest) {
        Long operatorId = userCashCheckAgreeBatchRequest.getOperatorId();
        String operatorName = userCashCheckAgreeBatchRequest.getOperatorName();

        //提现密码检测
        if (!userCashCheckAgreeBatchRequest.getSecPassword().equals(cpsUserCashConfig.getSecPassword())) {
            throw new BaseException(CpsUserCashExceptionEnum.SEC_PASSWORD_WRONG.getCode(), CpsUserCashExceptionEnum.SEC_PASSWORD_WRONG.getMessage());
        }
        //请选择信息
        if (userCashCheckAgreeBatchRequest.getIdStr() == null || "".equals(userCashCheckAgreeBatchRequest.getIdStr())) {
            throw new BaseException(CpsUserCashExceptionEnum.CHECKBOX_NO);
        }
        //获取批量打款逗号分隔组成的数组
        String[] idArr = userCashCheckAgreeBatchRequest.getIdStr().split(",");
        for (int i = 0; i < idArr.length; i++) {
            Message message = new Message("cpsUserCashCheckBatch", rocketMqConfig.getTag(), "", JSONObject.toJSONBytes(new CpsUserCashEvent(Integer.valueOf(idArr[i]), operatorId, operatorName)));
            producerBean.send(message, "cpsUserCashCheckBatch");
        }
        return true;
    }

    /**
     * 全部审核同意并打款
     * 打款失败，资金返还钱包
     */
    public Boolean checkAgreeAll(CpsUserCashCheckAgreeAllRequest userCashCheckAgreeAllRequest) {
        Long operatorId = userCashCheckAgreeAllRequest.getOperatorId();
        String operatorName = userCashCheckAgreeAllRequest.getOperatorName();
        QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("status", CpsUserCashStatusEnum.STATUS_APPLY.getCode());
        queryWrapper.eq("del_flag", DelFlag.NORMAL);
        //用户注册手机号
        if (userCashCheckAgreeAllRequest.getPhone() != null && !"".equals(userCashCheckAgreeAllRequest.getPhone())) {
            //根据手机号查询用户ID【用户服务提供接口】
            Integer uid = iUserExternalService.getUidByMobile(userCashCheckAgreeAllRequest.getPhone());
            if (uid != null && uid > 0) {
                queryWrapper.eq("uid", uid);
            } else {
                queryWrapper.eq("uid", DelFlag.NORMAL);
            }
        }
//        //提现状态: 0-申请中 1-提现处理中 2-审核失败 3-提现到账 4-提现失败
//        if (userCashCheckAgreeAllRequest.getStatus() != null) {
//            queryWrapper.eq("status", userCashCheckAgreeAllRequest.getStatus());
//        }
        //提现账户类型: 1-银行卡 2-支付宝
        if (userCashCheckAgreeAllRequest.getCashType() != null && userCashCheckAgreeAllRequest.getCashType() > 0) {
            queryWrapper.eq("cash_type", userCashCheckAgreeAllRequest.getCashType());
        }
        //创建开始时间
        if (userCashCheckAgreeAllRequest.getBeginTime() != null && !"".equals(userCashCheckAgreeAllRequest.getBeginTime())) {
            queryWrapper.ge("create_time", userCashCheckAgreeAllRequest.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //创建结束时间
        if (userCashCheckAgreeAllRequest.getEndTime() != null && !"".equals(userCashCheckAgreeAllRequest.getEndTime())) {
            queryWrapper.le("create_time", userCashCheckAgreeAllRequest.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //审核开始时间
        if (userCashCheckAgreeAllRequest.getCheckBeginTime() != null && !"".equals(userCashCheckAgreeAllRequest.getCheckBeginTime())) {
            queryWrapper.ge("check_time", userCashCheckAgreeAllRequest.getCheckBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //审核结束时间
        if (userCashCheckAgreeAllRequest.getCheckEndTime() != null && !"".equals(userCashCheckAgreeAllRequest.getCheckEndTime())) {
            queryWrapper.le("check_time", userCashCheckAgreeAllRequest.getCheckEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //支付开始时间
        if (userCashCheckAgreeAllRequest.getPayBeginTime() != null && !"".equals(userCashCheckAgreeAllRequest.getPayBeginTime())) {
            queryWrapper.ge("pay_time", userCashCheckAgreeAllRequest.getPayBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //支付结束时间
        if (userCashCheckAgreeAllRequest.getPayEndTime() != null && !"".equals(userCashCheckAgreeAllRequest.getPayEndTime())) {
            queryWrapper.le("pay_time", userCashCheckAgreeAllRequest.getPayEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        //提现密码检测
        if (!userCashCheckAgreeAllRequest.getSecPassword().equals(cpsUserCashConfig.getSecPassword())) {
            throw new BaseException(CpsUserCashExceptionEnum.SEC_PASSWORD_WRONG.getCode(), CpsUserCashExceptionEnum.SEC_PASSWORD_WRONG.getMessage());
        }
        List<CpsUserCash> userCashes = userCashMapper.selectList(queryWrapper);
        List<Integer> idList = userCashes.stream().map(CpsUserCash::getId).collect(Collectors.toList());
        if (idList.isEmpty()) {
            throw new BaseException(CpsUserCashExceptionEnum.INFO_NO_EXIST);
        }
        int[] idArr = idList.stream().mapToInt(Integer::valueOf).toArray();
        for (int i = 0; i < idArr.length; i++) {
            Message message = new Message("cpsUserCashCheckAll", rocketMqConfig.getTag(), "", JSONObject.toJSONBytes(new CpsUserCashEvent(Integer.valueOf(idArr[i]), operatorId, operatorName)));
            producerBean.send(message, "cpsUserCashCheckAll");
        }
        return true;
    }

    /**
     * 提现账户类型--对照字典
     */
    public Map<Integer, String> getCashType() {
        Map<Integer, String> m = new HashMap<>();
        m.put(CpsCashTypeEnum.CASH_BANKCARD.getCode(), CpsCashTypeEnum.CASH_BANKCARD.getDesc());
        m.put(CpsCashTypeEnum.CASH_ALIPAY.getCode(), CpsCashTypeEnum.CASH_ALIPAY.getDesc());
        return m;
    }

    /**
     * 提现状态--对照字典
     */
    public Map<Integer, String> getStatus() {
        Map<Integer, String> m = new HashMap<>();
        m.put(CpsCashStatusEnum.STATUS_APPLY.getCode(), CpsCashStatusEnum.STATUS_APPLY.getDesc());
        m.put(CpsCashStatusEnum.STATUS_AUDIT_PASSED.getCode(), CpsCashStatusEnum.STATUS_AUDIT_PASSED.getDesc());
        m.put(CpsCashStatusEnum.STATUS_AUDIT_FAILED.getCode(), CpsCashStatusEnum.STATUS_AUDIT_FAILED.getDesc());
        m.put(CpsCashStatusEnum.STATUS_CASH_ACCOUNT.getCode(), CpsCashStatusEnum.STATUS_CASH_ACCOUNT.getDesc());
        m.put(CpsCashStatusEnum.STATUS_CASH_FAILED.getCode(), CpsCashStatusEnum.STATUS_CASH_FAILED.getDesc());
        return m;
    }

    /**
     * 审核状态--对照字典
     */
    public Map<Integer, String> getCheckStatus() {
        Map<Integer, String> m = new HashMap<>();
        m.put(CpsUserCashStatusEnum.CHECK_STATUS_PASSED.getCode(), CpsUserCashStatusEnum.CHECK_STATUS_PASSED.getMessage());
        m.put(CpsUserCashStatusEnum.CHECK_STATUS_FAILED.getCode(), CpsUserCashStatusEnum.CHECK_STATUS_FAILED.getMessage());
        return m;
    }

    /**
     * 个人打款通用方法
     * Response(code = 0000, message = 操作成功, request_id = 3221010e15524fcca5c3c75a202a6ae5, data = { order_id = ali1597126400759588, pay = 0.01, ref = 432643765304340482 })
     * Response(code = 0000, message = 操作成功, request_id = 4abfba572bee4303b6e698f9e3e621f5, data = { order_id = bank1597127059802588, pay = 0.01, ref = 432646382399042202 })
     */
    private Boolean singlePay(int userCashId) {
        boolean result = false;
        boolean isPay = false;
        //查询信息
        QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", CpsCashStatusEnum.STATUS_AUDIT_PASSED.getCode());
        //queryWrapper.in("status", Arrays.asList(CashStatusEnum.STATUS_AUDIT_PASSED.getCode(), CashStatusEnum.STATUS_CASH_FAILED.getCode()));
        queryWrapper.eq("del_flag", DelFlag.NORMAL);
        queryWrapper.eq("id", userCashId);
        CpsUserCash userCash = userCashMapper.selectOne(queryWrapper);
        if (userCash == null) {
            throw new BaseException(CpsUserCashExceptionEnum.INFO_NO_EXIST.getCode(), CpsUserCashExceptionEnum.INFO_NO_EXIST.getMessage());
        }
        /**
         * 云账户
         * 个人银行卡
         */
        //公共信息
        String yzhMess = OrderUtil.getMess();
        int yzhTimestamp = Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000));
        String yzhSignType = Property.getProperties(ConfigPath.YZH_SIGN_TYPE);
        String yzhDealerId = Property.getProperties(ConfigPath.YZH_DEALERID);
        String yzhBrokerId = Property.getProperties(ConfigPath.YZH_BROKERID);
        if (userCash.getCashType() == CpsCashTypeEnum.CASH_BANKCARD.getCode().byteValue()) {
            /*
             * ⾃动和实时结算⾄银⾏卡
             * 转账给个⼈银⾏卡账户，通道限制单笔最低0.01
             * 银⾏卡通道单笔⽀付有0.5元成本（成本由云账户承担），建议商户单笔银⾏卡付款⼤于
50元         */
            //银行卡
            String yzhOrderIdBankCard = OrderUtil.getOrderId(OrderPrefixEnum.BANK_CARD_ORDER.getValue());
            //String yzhNotifyUrlBankCard = Property.getProperties(ConfigPath.YZH_BACKNOTIFY_URL);
            String yzhNotifyUrlBankCard = cpsUserCashConfig.getYzhBackNotify();
            String yzhGetUrlBankCard = Property.getUrl(ConfigPath.YZH_BANK_CARD_REAL_TIME_ORDER);
            //姓名、身份证号、银行卡号、实际到账金额
            String yzhRealName = userCash.getCashUserName();
            String yzhCardNo = userCash.getCashAccount();
            String yzhPhoneNo = "";
            String yzhIdCard = userCash.getCashIdCard();
            String yzhPay = userCash.getCashAmount().toString();
            String yzhPayRemark = "银⾏卡实时下单";
            Map<String, Object> yzhResultBankCard = null;
            try {
                yzhResultBankCard = HttpUtil.post(
                        Request.builder()
                                .mess(yzhMess)
                                .timestamp(yzhTimestamp)
                                .sign_type(yzhSignType)
                                .build().encData(
                                BankCardOrderRequest.builder()
                                        .order_id(yzhOrderIdBankCard)
                                        .dealer_id(yzhDealerId)
                                        .broker_id(yzhBrokerId)
                                        .real_name(yzhRealName)
                                        .card_no(yzhCardNo)
                                        .phone_no(yzhPhoneNo)
                                        .id_card(yzhIdCard)
                                        .pay(yzhPay)
                                        .pay_remark(yzhPayRemark)
                                        .notify_url(yzhNotifyUrlBankCard)
                                        .build()
                        ), yzhGetUrlBankCard);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //公共返回方法
            Map<String, String> returnMap = sysoutResult(yzhResultBankCard);
            //支付状态
            int payStatus;
            //支付返回码描述
            String payMsg;
            //云账户订单号
            String payNo = "";
            //网关返回码
            String gatewayCode;
            //网关返回码描述
            String gatewayMsg;
            String statusCode = returnMap.get("statusCode");
            String yzhCode = returnMap.get("yzhCode");
            String yzhData = returnMap.get("yzhData");
            String yzhMessage = returnMap.get("yzhMessage");
            String yzhRequestId = returnMap.get("yzhRequestId");
            String parameters = "商户订单号：" + yzhOrderIdBankCard + " , 用户姓名：" + yzhRealName + " , 银行卡帐号: " + yzhCardNo + " , 手机号: " + yzhPhoneNo + " , 身份证号: " + yzhIdCard + " , 提现金额: " + yzhPay + " , 备注信息: " + yzhPayRemark;
            if ("200".equals(statusCode)) {
                gatewayCode = statusCode;
                gatewayMsg = "请求成功";
                payStatus = CpsCashStatusEnum.STATUS_AUDIT_PASSED.getCode();
                payMsg = "网关返回码：" + gatewayCode + " , 网关返回码描述：" + gatewayMsg + " , 请求ID：" + yzhRequestId + " , 请求返回码：" + yzhCode + " , 请求返回码描述: " + yzhMessage;
                if ("0000".equals(yzhCode)) {
                    JSONObject jsonObject = JSON.parseObject(yzhData);
                    payMsg += " , 【商户订单号：" + jsonObject.get("order_id") + " , 综合服务平台流水号: " + jsonObject.get("ref") + " , 提现金额: " + jsonObject.get("pay") + "】";
                    payNo = jsonObject.get("order_id").toString();
                }
                isPay = true;
            } else {
                gatewayCode = statusCode;
                gatewayMsg = "请求异常，请联系管理员";
                payStatus = CpsCashStatusEnum.STATUS_CASH_FAILED.getCode();
                payMsg = "网关返回码：" + gatewayCode + " , 网关返回码描述：" + gatewayMsg;
                //返还金额到钱包
                WalletInOrOutRequest walletInOrOutRequest = new WalletInOrOutRequest();
                walletInOrOutRequest.setAmount(userCash.getCashAmount());
                walletInOrOutRequest.setRemark(CpsWalletTypeEnum.FAIL_WITHDRAW_IN.getMsg());
                walletInOrOutRequest.setUserId(userCash.getUid());
                walletInOrOutRequest.setType(CpsWalletTypeEnum.FAIL_WITHDRAW_IN.getCode());
                walletInOrOutRequest.setOrderNo(userCash.getOrderNo());
                walletInOrOutRequest.setOrderId(userCash.getId());
                adminCpsWalletInOrOutService.walletIn(walletInOrOutRequest);
            }
            // 更新支付状态
            userCash.setStatus((byte) payStatus);
            userCash.setPayTime(new Date());
            userCash.setPayCode(yzhCode);
            userCash.setPayMsg(payMsg);
            userCash.setPayNo(payNo);
            userCash.setParameters(parameters);
            userCash.setGatewayCode(gatewayCode);
            userCash.setGatewayMsg(gatewayMsg);
            userCash.setCashAccount(yzhCardNo);
            userCash.setCashUserName(yzhRealName);
            int row = userCashMapper.updateById(userCash);
            if (row > 0) {
                if (isPay) {
                    result = true;
                }
            }
        } else if (userCash.getCashType() == CpsCashTypeEnum.CASH_ALIPAY.getCode().byteValue()) {
            //支付宝
            String yzhOrderIdAlipay = OrderUtil.getOrderId(OrderPrefixEnum.ALIPAY_ORDER.getValue());
            //String yzhNotifyUrlAlipay = Property.getProperties(ConfigPath.YZH_BACKNOTIFY_URL);
            String yzhNotifyUrlAlipay = cpsUserCashConfig.getYzhBackNotify();
            String yzhGetUrlAlipay = Property.getUrl(ConfigPath.YZH_ALIPAY_REAL_TIME_ORDER);
            String yzhCheckName = CheckNameEnum.NOCHECK.getValue();
            //姓名、身份证号、支付宝帐号、实际到账金额
            String yzhRealName = userCash.getCashUserName();
            String yzhIdCard = userCash.getCashIdCard();
            String yzhCardNo = userCash.getCashAccount();
            String yzhPay = userCash.getCashAmount().toString();
            String yzhPayRemark = "支付宝实时下单";
            //支付宝
            Map<String, Object> yzhResultAlipay = null;
            try {
                yzhResultAlipay = HttpUtil.post(
                        Request.builder()
                                .mess(yzhMess)
                                .timestamp(yzhTimestamp)
                                .sign_type(yzhSignType)
                                .build().encData(
                                AlipayOrderRequest.builder()
                                        .order_id(yzhOrderIdAlipay)
                                        .dealer_id(yzhDealerId)
                                        .broker_id(yzhBrokerId)
                                        .real_name(yzhRealName)
                                        .card_no(yzhCardNo)
                                        .id_card(yzhIdCard)
                                        .pay(yzhPay)
                                        .pay_remark(yzhPayRemark)
                                        .check_name(yzhCheckName)
                                        .notify_url(yzhNotifyUrlAlipay)
                                        .build()
                        ), yzhGetUrlAlipay);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //公共返回方法
            Map<String, String> returnMap = sysoutResult(yzhResultAlipay);
            //支付状态
            int payStatus;
            //支付返回码描述
            String payMsg;
            //云账户订单号
            String payNo = "";
            //网关返回码
            String gatewayCode;
            //网关返回码描述
            String gatewayMsg;
            String statusCode = returnMap.get("statusCode");
            String yzhCode = returnMap.get("yzhCode");
            String yzhData = returnMap.get("yzhData");
            String yzhMessage = returnMap.get("yzhMessage");
            String yzhRequestId = returnMap.get("yzhRequestId");
            String parameters = "商户订单号：" + yzhOrderIdAlipay + " , 用户姓名：" + yzhRealName + " , 收款人支付宝账户: " + yzhCardNo + " , 身份证号: " + yzhIdCard + " , 提现金额: " + yzhPay + " , 备注信息: " + yzhPayRemark;
            if ("200".equals(statusCode)) {
                gatewayCode = statusCode;
                gatewayMsg = "请求成功";
                payStatus = CpsCashStatusEnum.STATUS_AUDIT_PASSED.getCode();
                payMsg = "网关返回码：" + gatewayCode + " , 网关返回码描述：" + gatewayMsg + " , 请求ID：" + yzhRequestId + " , 请求返回码：" + yzhCode + " , 请求返回码描述: " + yzhMessage;
                if ("0000".equals(yzhCode)) {
                    JSONObject jsonObject = JSON.parseObject(yzhData);
                    payMsg += " , 【商户订单号：" + jsonObject.get("order_id") + " , 综合服务平台流水号: " + jsonObject.get("ref") + " , 提现金额: " + jsonObject.get("pay") + "】";
                    payNo = jsonObject.get("order_id").toString();
                }
                isPay = true;
            } else {
                gatewayCode = statusCode;
                gatewayMsg = "请求异常，请联系管理员";
                payStatus = CpsCashStatusEnum.STATUS_CASH_FAILED.getCode();
                payMsg = "网关返回码：" + gatewayCode + " , 网关返回码描述：" + gatewayMsg;
                //返还金额到钱包
                WalletInOrOutRequest walletInOrOutRequest = new WalletInOrOutRequest();
                walletInOrOutRequest.setAmount(userCash.getCashAmount());
                walletInOrOutRequest.setRemark(CpsWalletTypeEnum.FAIL_WITHDRAW_IN.getMsg());
                walletInOrOutRequest.setUserId(userCash.getUid());
                walletInOrOutRequest.setType(CpsWalletTypeEnum.FAIL_WITHDRAW_IN.getCode());
                walletInOrOutRequest.setOrderNo(userCash.getOrderNo());
                walletInOrOutRequest.setOrderId(userCash.getId());
                adminCpsWalletInOrOutService.walletIn(walletInOrOutRequest);
            }
            // 更新支付状态
            userCash.setStatus((byte) payStatus);
            userCash.setPayTime(new Date());
            userCash.setPayCode(yzhCode);
            userCash.setPayMsg(payMsg);
            userCash.setPayNo(payNo);
            userCash.setParameters(parameters);
            userCash.setGatewayCode(gatewayCode);
            userCash.setGatewayMsg(gatewayMsg);
            userCash.setCashAccount(yzhCardNo);
            userCash.setCashUserName(yzhRealName);
            int row = userCashMapper.updateById(userCash);
            if (row > 0) {
                if (isPay) {
                    result = true;
                }
            }
        }
        return result;
    }

    /**
     * 云账户
     * 订单查询
     */
    public String orderQuery(OrderQueryRequest orderQueryRequest) {
        //公共信息
        String yzhMess = OrderUtil.getMess();
        int yzhTimestamp = Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000));
        String yzhSignType = Property.getProperties(ConfigPath.YZH_SIGN_TYPE);
        String yzhDataType = "";
        String yzhGetUrlQuery = Property.getUrl(ConfigPath.YZH_ORDER_QUERY);
        //查询信息
        QueryWrapper<CpsUserCash> queryWrapper = new QueryWrapper<>();
        List<Integer> statusVals = new ArrayList<Integer>();
        statusVals.add(CpsCashStatusEnum.STATUS_CASH_ACCOUNT.getCode());
        statusVals.add(CpsCashStatusEnum.STATUS_CASH_FAILED.getCode());
        queryWrapper.eq("id", orderQueryRequest.getId()).in("status", statusVals).eq("del_flag", DelFlag.NORMAL);
        CpsUserCash userCash = userCashMapper.selectOne(queryWrapper);
        if (userCash == null) {
            throw new BaseException(CpsUserCashExceptionEnum.INFO_NO_EXIST.getCode(), CpsUserCashExceptionEnum.INFO_NO_EXIST.getMessage());
        }
        int cashType = userCash.getCashType();
        //默认银行卡类型
        String channel = cashType == 2 ? ChannelEnum.ALIPAY.getValue() : ChannelEnum.BANKCARD.getValue();
        String yzhOrderId = userCash.getPayNo();
        Map<String, Object> yzhResultQuery = null;
        try {
            yzhResultQuery = HttpUtil.get(
                    Request.builder()
                            .mess(yzhMess)
                            .timestamp(yzhTimestamp)
                            .sign_type(yzhSignType)
                            .build().encData(
                            com.jumi.microservice.yzhpay.dto.request.OrderQueryRequest.builder()
                                    .order_id(yzhOrderId)
                                    .channel(channel)
                                    .data_type(yzhDataType)
                                    .build()
                    ), yzhGetUrlQuery);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //公共返回方法
        Map<String, String> returnMap = sysoutResult(yzhResultQuery);
        return returnMap.toString();
    }
}
